package com.mega;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsoluteLayout;
import android.widget.Button;

public class Test3Activity extends Activity {
    byte[] xxxcid = {'X', 'X', 'X', 'C', 'I', 'D'};//Э����ݰ�ͷ
    byte[] localAddr = {'Z', '0', '0', '0', '1'};//������ 
    byte[] localip = {(byte) 0xC0, (byte) 0xA8, 2, 7};//����IP
    byte[] remoteAddr = {'M', '0', '0', '0', '1', '9'};//�Է����
    byte[] remoteip = {(byte) 192, (byte) 168, 2, 17};//�Է�ip
    int local_port = 8302;
	int server_port = 8302; 
	byte[] message = new byte[1024];
	InetAddress local = null;  
    InetAddress remote;
    
    DatagramSocket datagramSocket = null;
    DatagramPacket datagramPacket = null;
    
	Button button1;
	Button buttonPlay;
	
	CircularBuf cbuf = new CircularBuf();
	
	//定义一个环形缓冲区
	public class CircularBuf 
	{  
	    int NMAX=2*1024*1024;//最大内存数量
	    int iput = 0; //队列写指针  
	    int iget = 0; //队列读指针  
	    int n = 0;//队列元素数量
	    byte buffer[]=new byte[NMAX]; //缓冲区
	    
	    public int addring(int i)
	    {  
	         return (i+1) == NMAX ? 0 : i+1;  
	    }
	    
	    //默认拷贝1024个字节
	    public byte[] get(int size) {
	    	byte b[] = new byte[1024];
	        int pos;  
	        if (n>0){  
	            pos = iget;  
	            iget = addring(iget);  
	            n--;  
	            System.out.println("get-->"+buffer[pos]);  
	            return buffer;  
	      
	        }else {  
	            System.out.println("Buffer is Empty");  
	            //return 0.0;  
	        }
	        System.arraycopy(buffer, iget, b, 0, size);
			return b;  
	    }  
	    
	    
	    //插入一个数组
	    public void put(byte z[])
	    {  
	        if (n+z.length<NMAX)
	        {  
	            //buffer[iput]=z;
	        	System.arraycopy(z, 0, buffer, n, z.length);
	            System.out.println("put<--"+buffer[iput]);  
	            iput = addring(iput);  
	            n += n+z.length;
	        }else  System.out.println("Buffer is full");  
	    }

	    //第一个参数是数组,索引,长度
		public void put(byte[] b, int index, int length) 
		{
			if (n + length < NMAX)
			{
				System.arraycopy(b, index, buffer, n, length);
				n += length;
				Log.i("n = ", String.valueOf(n));
			}
		}  
	}
	
	//�����߳�
	Runnable decodeRunner = new Runnable()
	{
		@Override
		public void run() {
			
			
		}
		
	};
	
	//��Ƶ�����߳�
	Runnable receiveRunner = new Runnable()
	{
		@Override
		public void run() {
			String esFileName = "/data/Video/s.es";
			//OutputStreamWriter writer = null;
			FileOutputStream outStream = null;
			File file = new File(esFileName);  
			try {
				outStream = new FileOutputStream(file);
				//writer = new OutputStreamWriter(outStream,"gb2312");
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}

			while(true)
			{
				byte[] buffer = new byte[2048];
				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
				try {
					datagramSocket.receive(packet);
					if(buffer[8] == 0x08)
					{
						cbuf.put(buffer, 77, packet.getLength()-77);
						outStream.write(buffer, 77, packet.getLength()-77);//����Ƶ���д���ļ�
					}
					//Log.w(this.toString(), Integer.toString(packet.getData().length));
					//Log.w(this.toString(), Integer.toString(packet.getPort()));
					InetAddress sendIP = packet.getAddress();
					//Log.w(this.toString(), sendIP.getHostAddress());
					//Log.i(this.toString(), Integer.toString(packet.getLength()));//��ʾÿ���յ��������
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();  
				}  
			}
		}
		
	};
	
	OnClickListener buttonPlayClickListener = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			/*
			//VideoView vv = new VideoView(this); 
			com.mega.VideoView vv = new com.mega.VideoView(null);
			vv.bringToFront();
			vv.playVideo("/sdcard/Video/s.es");
			*/
			com.mega.VideoView vv = (VideoView) findViewById(R.id.videoview);
			vv.bringToFront();
			vv.playVideo("/data/Video/s.es");
			vv.postInvalidate();
		}
		
	};
	
	OnClickListener button1ClickListener = new OnClickListener()
	{
		    public void onClick(View v) {
				System.arraycopy(xxxcid, 0, message, 0, xxxcid.length);
				System.arraycopy(localAddr, 0, message, 10, localAddr.length);					
				System.arraycopy(localip, 0, message, 29, localip.length);
				System.arraycopy(remoteAddr, 0, message, 33, remoteAddr.length);					
				System.arraycopy(remoteip, 0, message, 53, remoteip.length);
				
				message[6] = (byte) 0x98;
				message[7] = (byte) 0x01;
				message[8] = (byte) 0x01;						
				datagramPacket = new DatagramPacket(message,  
				        message.length, local, server_port);
				datagramPacket.setAddress(remote);
				try {
					datagramSocket.send(datagramPacket);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				new Thread(receiveRunner).start();
			}
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*
		com.mega.VideoView vv = new com.mega.VideoView(this);
		vv.bringToFront();
		this.addContentView(vv, new AbsoluteLayout.LayoutParams(300, 300, 300, 300));
		vv.playVideo("/sdcard/Video/s.es");
		*/
        
        setContentView(R.layout.main);     
        
        //Log.e("环形缓冲区长度", String.valueOf(cbuf.get(1024).length));
           
        button1 = (Button) this.findViewById(R.id.button1);   
        buttonPlay = (Button) this.findViewById(R.id.buttonPlay);
        try {
			remote = InetAddress.getByAddress(remoteip);
		} catch (UnknownHostException e2) {
			e2.printStackTrace();
		}
        
        try {
			datagramSocket = new DatagramSocket(local_port);
			datagramSocket.setReceiveBufferSize(65536);
		} catch (SocketException e1) {
			e1.printStackTrace();
		}
        
        button1.setOnClickListener(button1ClickListener);
        buttonPlay.setOnClickListener(buttonPlayClickListener);
        /*
        buttonPlay.setOnClickListener(new OnClickListener()
    	{

    		@Override
    		public void onClick(View v) {
    			//VideoView vv = new VideoView(this); 
    			com.mega.VideoView vv = new com.mega.VideoView(buttonPlay.getContext());
    			vv.playVideo("/sdcard/Video/s.es");
    		}
    		
    	}); 
    	*/	
    }
}